/**
 * File util for uploading and downloading
 */
var fs = require('fs');
var utils = require('./utils').Utils;

var fileDirectory = __dirname.replace('services/utils', 'data/file/');

exports.uploadFile = function(req, res) {
	
	var files = req.files;
	var fileName = req.body.name;
	console.log(__dirname);
	if (req.user) {
		if (files) {
			
			if (files.myFile) {
				
				var filePath = files.myFile.path;
				var fileType = utils.getFileExtension(filePath);
				
				if(fileType == 'xlsx') {
					if(fileName) {
						fileName+= '.'+fileType;
					} else {
						fileName = files.myFile.name;
					}
					
					//Store the file specific to user folder inside /data/file/users
					fileDirectory = fileDirectory+'users/'+req.user.userName;
					utils.makeDirectory(fileDirectory, 1, function() {
						fs.readFile(filePath, function(err, data) {
							
							fs.writeFile(fileDirectory+'/'+fileName, data, function(err) {
								if(err){
									console.log("There is error while storing the file in local directory!!!");
									res.status(400).send({error: err, message: 'Error while storing the file'});
								}
								else{
									console.log("Successfully moved the file in local directory.");
									res.send({message:'Successfully uploaded the file'});
								}
							});
						});
					});
				} else {
					res.status(400).send({message: 'The uploaded file should be excel with extension (xlsx)'});
				}
			}
		}
	} else {
		res.status(401).send({message: 'Unauthorized user. Please login'});
	}
};

